<?php

namespace AdminBundle\Controller;

use AdminBundle\Entity\BaseDevice;
use AdminBundle\Entity\BaseWebchatUser;
use AdminBundle\Entity\BaseWebchatUserExtra;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
use AdminBundle\Utility\Constant;

/**
 * Basewebchatuser controller.
 *
 * @Route("basewebchatuser")
 */
class BaseWebchatUserController extends Controller
{
    /**
     * Lists all webchat entities by device_id.
     *
     * @Route("/device/{id}/{has_default}", defaults={"id"="0", "has_default" = ""}, name="basewebchatuser_by_device")
     * @Method("GET")
     */
    public function deviceByGroupAction(Request $request, $id, $has_default)
    {
        $result = [];
        if ($has_default != "") {
            $result[] = ['key' => "", "value" => "全部"];
        }
        $baseWebchatUsers = $this->getDoctrine()->getRepository('AdminBundle:BaseWebchatUser')->findBy(['deviceId' => $id]);

        foreach ($baseWebchatUsers as $baseWebchatUser) {
            $value = $baseWebchatUser->getNickname() . ',' . $baseWebchatUser->getUserName();
            $result[] = ['key' => $baseWebchatUser->getUserName(), 'value' => $value];
        }
        return $this->json($result);
    }


    /**
     * Lists all baseWebchatUser entities.
     *
     * @Route("/", name="basewebchatuser_index")
     * @Method("GET")
     */
    public function indexAction(Request $request)
    {
        $page = $request->get("page");
        $page = is_numeric($page) ? $page : 1;
        $keyword = $request->get('keyword');
        $date_range = $request->get('date_range');
        $device_group = $request->get('device_group');
        $device = $request->get('device');
        if (!empty($date_range)) {
            $date_range = explode(" - ", $date_range);
            $starttime = $date_range[0];
            $endtime = $date_range[1];
        } else {
            $starttime = $endtime = null;
        }

        $starttime = date("Y-m-d", strtotime($starttime ?: "-3 day"));
        $endtime = date("Y-m-d", strtotime($endtime ?: "+1 day"));

        $params = ['keyword' => $keyword, 'starttime' => $starttime, 'endtime' => $endtime,
            'device_group' => $device_group, 'device' => $device];

        $result = $this->getDoctrine()->getRepository('AdminBundle:BaseWebchatUser')->pageQuery($params, $page);

        $em = $this->getDoctrine()->getManager();
        // 终端组
        $baseGroup = $em->getRepository('AdminBundle:BaseGroup')->findAll();
        $params['baseGroups'] = $baseGroup;
        // 终端
        $baseDevice = $em->getRepository('AdminBundle:BaseDevice')->findAll();
        $params['baseDevices'] = $baseDevice;

        return $this->render('AdminBundle:basewebchatuser:index.html.twig', array_merge([
            'dataSources' => $result['list'],
            'querystring' => http_build_query($params),
            'page' => $result['page'],
        ], $params));
    }

    /**
     * Creates a new baseWebchatUser entity.
     *
     * @Route("/new", name="basewebchatuser_new")
     * @Method({"GET", "POST"})
     */
    public function newAction(Request $request)
    {
        $baseWebchatUser = new Basewebchatuser();
        $form = $this->createForm('AdminBundle\Form\BaseWebchatUserType', $baseWebchatUser, Constant::FORM_ATTR_CLASS);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $baseWebchatUser->setCtime(new \DateTime())
                ->setCreator($this->getUser()->getUsername())
                ->setIp($request->getClientIp());

            $deviceId = 0;
            $deviceImei = '';
            $deivceName = '';
            if (($baseDevice = $form->getNormData()->getDeviceImei()) instanceof BaseDevice) {
                $deviceId = $baseDevice->getId();
                $deviceImei = $baseDevice->getImei();
                $deivceName = $baseDevice->getName();
            }
            $baseWebchatUser->setDeviceId($deviceId);
            $baseWebchatUser->setDeviceImei($deviceImei);
            $baseWebchatUser->setDeviceText($deivceName);

            $em = $this->getDoctrine()->getManager();
            $em->persist($baseWebchatUser);
            $em->flush();

            // 新增额外信息
            $baseWebchatUserExtra = $em->getRepository('AdminBundle:BaseWebchatUserExtra')->find($baseWebchatUser->getId());
            if ($baseWebchatUserExtra == null) {
                $baseWebchatUserExtra = new BaseWebchatUserExtra();
            }
            $baseWebchatUserExtra->setId($baseWebchatUser->getId());
            $baseWebchatUserExtra->setLastRequestIp($request->getClientIp());
            $baseWebchatUserExtra->setLastReportTime(new \DateTime());
            $baseWebchatUserExtra->setLastRequestTime(new \DateTime());

            $em->persist($baseWebchatUserExtra);
            $em->flush();

            return $this->redirectToRoute('basewebchatuser_show', array('id' => $baseWebchatUser->getId()));
        }

        return $this->render('AdminBundle:basewebchatuser:new.html.twig', array(
            'baseWebchatUser' => $baseWebchatUser,
            'form' => $form->createView(),
        ));
    }

    /**
     * Finds and displays a baseWebchatUser entity.
     *
     * @Route("/{id}", name="basewebchatuser_show")
     * @Method("GET")
     */
    public function showAction(BaseWebchatUser $baseWebchatUser)
    {
        $deleteForm = $this->createDeleteForm($baseWebchatUser);

        return $this->render('AdminBundle:basewebchatuser:show.html.twig', array(
            'dataSource' => $baseWebchatUser,
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Displays a form to edit an existing baseWebchatUser entity.
     *
     * @Route("/{id}/edit", name="basewebchatuser_edit")
     * @Method({"GET", "POST"})
     */
    public function editAction(Request $request, BaseWebchatUser $baseWebchatUser)
    {
        $deleteForm = $this->createDeleteForm($baseWebchatUser);
        $editForm = $this->createForm('AdminBundle\Form\BaseWebchatUserType', $baseWebchatUser, Constant::FORM_ATTR_CLASS);
        $editForm->handleRequest($request);

        if ($editForm->isSubmitted() && $editForm->isValid()) {
            $form = $editForm;

            $deviceId = 0;
            $deviceImei = '';
            $deivceName = '';
            if (($baseDevice = $form->getNormData()->getDeviceImei()) instanceof BaseDevice) {
                $deviceId = $baseDevice->getId();
                $deviceImei = $baseDevice->getImei();
                $deivceName = $baseDevice->getName();
            }
            $baseWebchatUser->setDeviceId($deviceId);
            $baseWebchatUser->setDeviceImei($deviceImei);
            $baseWebchatUser->setDeviceText($deivceName);

            $this->getDoctrine()->getManager()->flush();

            return $this->redirectToRoute('basewebchatuser_edit', array('id' => $baseWebchatUser->getId()));
        }
        //设置select 对应属性默认值
        $em = $this->getDoctrine()->getManager();
        if ($baseWebchatUser->getDeviceId()) {
            $baseDevice = $em->getRepository('AdminBundle:BaseDevice')->findOneById($baseWebchatUser->getDeviceId());
            $editForm->get('deviceImei')->setData($baseDevice);
        }

        return $this->render('AdminBundle:basewebchatuser:edit.html.twig', array(
            'dataSource' => $baseWebchatUser,
            'form' => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Deletes a baseWebchatUser entity.
     *
     * @Route("/{id}", name="basewebchatuser_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, BaseWebchatUser $baseWebchatUser)
    {
        $form = $this->createDeleteForm($baseWebchatUser);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->remove($baseWebchatUser);
            $em->flush();
        }

        return $this->redirectToRoute('basewebchatuser_index');
    }

    /**
     * Creates a form to delete a baseWebchatUser entity.
     *
     * @param BaseWebchatUser $baseWebchatUser The baseWebchatUser entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm(BaseWebchatUser $baseWebchatUser)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('basewebchatuser_delete', array('id' => $baseWebchatUser->getId())))
            ->setMethod('DELETE')
            ->getForm();
    }
}
